package com.lxb;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 螺旋数组
 */
public class SpiralOrder {

    public static void main(String[] args) {

        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};

        int rows = matrix.length;
        int cols = matrix[0].length;

        int elem = rows * cols;
        ArrayList<Integer> list = new ArrayList<Integer>();
        int left = 0;
        int right = cols-1;
        int top = 0;
        int bottom = rows-1;
        while (elem >= 1){
            for(int i = left;i<=right  && elem >= 1;i++){
                list.add(matrix[top][i]);
                elem--;
            }
            top++;
            for(int i=top;i<=bottom  && elem >= 1;i++){
                list.add(matrix[i][right]);
                elem--;
            }
            right--;
            for(int i=right;i>= left && elem >= 1;i--){
                list.add(matrix[bottom][i]);
                elem--;
            }
            bottom--;
            for(int i=bottom;i>= top && elem >= 1;i--){
                list.add(matrix[i][left]);
                elem--;
            }
            left++;
        }

        System.out.println(list);

    }

}
